package com.fig.zk;

import org.apache.zookeeper.*;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Description:
 * @Author: Flynn Vanderboom
 * @Data: 2021/7/14 20:38
 */

public class zkClient {


    private String connectString = "System102:2181,System103:2181,System104:2181";
    private int sessionTimeout = 2000;
    private ZooKeeper zooKeeper;


    @Before
    public void init() throws IOException {

        zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {


            @Override
            public void process(WatchedEvent watchedEvent) {
                List<String> children = null;
                try {
                    children = zooKeeper.getChildren("/", true);
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                for(String child :children){
                    System.out.println(child);
                }

                System.out.println("====================");
            }
        });
    }

    @Test
    public void create() throws InterruptedException, KeeperException {
        zooKeeper.create("/mole","molele".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }
    
    @Test
    public void getChildren() throws InterruptedException, KeeperException {
        List<String> children = zooKeeper.getChildren("/", true);
        for(String child :children){
            System.out.println(child);
        }
        System.out.println("====================");
        //延时
        Thread.sleep(Long.MAX_VALUE);
    }
}
